import React from 'react'
import { connect } from 'react-redux'
import { Icon, Popover } from 'antd'
import httpFetch from 'share/httpFetch'
import { messages, queryCurrencyPrecision, removeArryItem } from "share/common";
import SearchArea from 'components/search-area.js';
import ExportModal from 'components/template/export-modal/export-modal';
import ResizeTable from 'components/resize-table'

class PaymentBatch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      page: 0,
      pageSize: 10,
      data: [],
      sort: '',
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: this.onChangePagerSize,
        pageSizeOptions: ['10','20','50','100','200']
      },
      searchForm: [
        {type: 'input', id: 'reimbursementBatchName', label: messages('financial-management.key268'/*放款批次*/)},
        {
          type: 'items', id: 'dateRange', items: [
            {type: 'date', id: 'paymentStartDate', label: messages('financial-management.key269'/*放款日期从*/)},
            {type: 'date', id: 'paymentEndDate', label: messages('financial-management.key270'/*放款日期到*/)}
          ]
        },
        {
          type: 'combobox',
          id: 'paymentBankAccount',
          label: messages('financial-management.key154'/*付款账号*/),
          placeholder: messages('financial-management.key271'/*请选择*/),
          options: [],
          getUrl: `/api/companyBankAuth/get/own/info/${props.user.userOID}`,
          method: 'get',
          labelKey: 'companyBank.bankAccountName',
          valueKey: 'companyBank.bankAccountNumber'
        },
        {
          type: 'combobox',
          id: 'paymentCode',
          label: messages('financial-management.key272'/*支付方式*/),
          placeholder: messages('financial-management.key271'/*请选择*/),
          options: [],
          getUrl: `/payment/api/cash/payment/method/query/all`,
          method: 'get',
          labelKey: 'description',
          valueKey: 'paymentMethodCode'
        },
        {
          type: 'select', id: 'currencyCode', label: messages('common.currency'), options: [],
          getUrl: `/api/currency/status/query/by/setOfBooksId?userOId=${props.user.userOID}`,
          labelKey: 'currency', valueKey: 'currency', method: 'get'
        },
        {
          type: 'items', id: 'priceRange', items: [
            {type: 'inputNumber', id: 'minTotalAmount', label: messages('financial-management.key196'/*金额从*/)},
            {type: 'inputNumber', id: 'maxTotalAmount', label: messages('financial-management.key197'/*金额至*/)}
          ]
        },
        {type: 'input', id: 'paymentChequeNo', label: messages('financial-management.key273'/*发票号*/)},
      ],
      searchParams: {
        reimbursementBatchName: null,
        paymentStartDate: undefined,
        paymentEndDate: undefined,
        currencyCode: null,
        minTotalAmount: null,
        maxTotalAmount: null,
        paymentBankAccount: null,
        paymentCode: null,
        paymentChequeNo: null
      },
      columns: [
        {title: messages('financial-management.key274'/*序号*/), dataIndex: "index", width: 48},
        {title: messages('financial-management.key275'/*放款批次*/), dataIndex: "reimbursementBatchName",
          render: text => (
            <Popover content={text}>
              {text}
            </Popover>
          )
        },
        {title: messages('financial-management.key276'/*付款账号*/), dataIndex: "paymentBankAccount", width: '15%'},
        {title: messages('financial-management.key277'/*放款日期*/), dataIndex: "paymentTime", width: 120, render: date => new Date(date.substr(0,10)).format('yyyy-MM-dd'),sorter: true},
        {title: messages('financial-management.key278'/*币种*/), dataIndex: "paymentCurrency", width: 48},
        {title: messages('financial-management.key279'/*总金额*/), dataIndex: "totalAmount", width: '15%',align: "right", render:(value,record) => this.filterMoney(value,queryCurrencyPrecision(record.paymentCurrency)),sorter: true},
        {title: messages('financial-management.key272'/*支付方式*/), dataIndex: "paymentType", width: '10%'},
        {title: messages('financial-management.key273'/*发票号*/), dataIndex: "paymentChequeNo", width: '10%'},
        {title: messages('financial-management.key280'/*报盘文件*/), dataIndex: "reimbursementBatchOID", width: '10%', className: 'center-icon',
          render: (id, record) => id ?  <ExportModal
            type={"btn"}
            exportTitle={<Icon type="download" />}
            exportType="REIMBURSEMENT_BATCH"
            exportCondition={{
              reimbursementBatchOID: record.reimbursementBatchOID
            }}
            exportCommand={'BATCH'}/> : null},
        {title: messages('financial-management.key769')/*报盘明细*/, dataIndex: "batchType", key: 1002, width: '10%', className: 'center-icon',
          render: (batchType, record) => <ExportModal
            type={"btn"}
            exportTitle={<Icon type="download" />}
            exportType="REIMBURSEMENT_BATCH"
            exportCondition={{
              reimbursementBatchOID: record.reimbursementBatchOID
            }}
            exportCommand={'BATCH_DETAIL'}/>}
      ],
      reportFile: false,
      reimbDetail: false,
      loanDetail: false
    };
  }


  componentWillMount(){
    this.handleData();
    this.getList();
  }

  getList = () => {
    this.setState({loading: true});
    let temp = this.state.searchParams;
    temp.page = this.state.page;
    temp.size = this.state.pageSize;
    const { sort } = this.state;
    if(sort) {
      let sortedField = sort.split(',')[0];
      temp.sortedField = sortedField;
      temp.isAsc = sort.split(',')[1] === 'ASC' ? true : false;
    }
    const { pagination } = this.state;
    httpFetch.post(`/api/reimbursement/batch/get`,temp).then(res => {
      let data = res.data.rows.map((item, index) => {
        item.index = this.state.page * this.state.pageSize + index + 1;
        return item;
      });
      pagination.total = Number(res.data.total);
      pagination.current = this.state.page + 1;
      this.setState({
        loading: false,
        data,
        pagination
      });
    }).catch(e => {
      this.setState({loading: false});
    })
  };

  onChangePagerSize = (current, size) => {
    if(size !== this.state.pageSize)
      this.setState({
        page: 0,
        pageSize: size
      })
  };

  handleTableChange = (pagination, filters, sorter) => {
    let page =  pagination.current;
    let sort = '';
    if(sorter.order){
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`
    }
    this.setState({
      page: page - 1,
      sort
    }, ()=>{
      this.getList();
    })
  };
  search = (result) => {
    result.paymentStartDate = result.paymentStartDate ? result.paymentStartDate.format('YYYY-MM-DD 00:00:00'): undefined;
    result.paymentEndDate = result.paymentEndDate ? result.paymentEndDate.format('YYYY-MM-DD 23:59:59') : undefined;
    let searchParams = {
      reimbursementBatchName: result.reimbursementBatchName,
      paymentStartDate: result.paymentStartDate,
      paymentEndDate: result.paymentEndDate,
      currencyCode: result.currencyCode,
      minTotalAmount: result.minTotalAmount,
      maxTotalAmount: result.maxTotalAmount,
      paymentBankAccount: result.paymentBankAccount,
      paymentCode: result.paymentCode,
      paymentChequeNo: result.paymentChequeNo
    };
    this.setState({
      searchParams: searchParams,
      loading: true,
      page: 0
    }, () => {
      this.getList();
    })
  };

  clear = () => {
    this.setState({
      searchParams: {
        reimbursementBatchName: null,
        paymentStartDate: undefined,
        paymentEndDate: undefined,
        currencyCode: null,
        minTotalAmount: null,
        maxTotalAmount: null,
        paymentBankAccount: null,
        paymentCode: null,
        paymentChequeNo: null
      }
    },() => {
      this.getList();
    })
  };
  //渲染处理数据源
  handleData = () => {
    let {columns,searchForm} =this.state;
    if(this.checkFunctionProfiles('pay.choice.banknum', [false, undefined])){
      removeArryItem(columns, columns.filter(item => item.dataIndex === 'paymentBankAccount')[0]);
      removeArryItem(columns, columns.filter(item => item.dataIndex === 'paymentType')[0]);
      removeArryItem(columns, columns.filter(item => item.dataIndex === 'paymentChequeNo')[0]);
      removeArryItem(searchForm, searchForm.filter(item => item.id === 'paymentBankAccount')[0]);
      removeArryItem(searchForm, searchForm.filter(item => item.id === 'paymentCode')[0]);
      removeArryItem(searchForm, searchForm.filter(item => item.id === 'paymentChequeNo')[0]);
      this.setState({columns,searchForm})
    }
  };
  render(){

    const { searchForm, data, loading, columns, pagination } = this.state;
    return (
      <div>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}
        />
        <div className="table-header">
          <div className="table-header-title">{messages('common.total1',{total:`${pagination.total}`})}</div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          bordered
          pagination={pagination}
          loading={loading}
          size="middle"
          onChange={this.handleTableChange}
          rowKey="reimbursementBatchOID"
        />
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    companyConfiguration: state.login.companyConfiguration,
    company: state.login.company,
    language: state.main.language,
    user: state.login.user,

  }
}

export default connect(mapStateToProps)(PaymentBatch);
